#include <string>
#include <unordered_map>

#include "dbc.hpp"
using std::string;
using std::unordered_map;

void regist(string& url, unordered_map<string, string>& ump) {
  char* name = ump["name"].data();
  char* pwd = ump["pwd"].data();
  char query[1024];
  sprintf(query, "insert into clients values('%s', '%s')", name, pwd);
  db_insert(query);
  url = "/chatting.html";
}

void loginCheck(string& url, unordered_map<string, string>& ump) {
  char* name = ump["name"].data();
  char* pwd = ump["pwd"].data();
  char query[1024];
  sprintf(query, "select * from clients where name='%s' and pwd='%s'", name,
          pwd);
  if (!db_search(query)) {
    url = "/loggin1.html";
  }else url = "/chatting.html";
}

void update_ump(string& url, int pos) {
  unordered_map<string, string> ump;
  string paras = url.substr(pos + 1);
  paras += '&';
  url = url.substr(0, pos);
  pos = paras.find('&');
  while (pos != paras.npos) {
    string item = paras.substr(0, pos);
    paras = paras.substr(pos + 1);
    int i = item.find('=');
    string key = item.substr(0, i);
    item = item.substr(i + 1); 
    ump[key] = item;
    pos = paras.find('&');
  }
  if (url == "/loggin.html" || url == "/loggin1.html") loginCheck(url, ump);
  else if(url == "/regist.html") regist(url, ump);
}